/**
 * 文档编辑页
 * Phase 1: 前端 MVP 使用
 * 
 * 功能：
 * - 创建/编辑文档
 * - Monaco Editor 编辑
 * - 实时预览
 * - 表单验证
 * - 自动保存
 */

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Container } from '@/components/ui/container';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import MonacoMarkdownEditor from '@/components/documentation/monaco-markdown-editor';
import MarkdownRenderer from '@/components/documentation/markdown-renderer';
import MarkdownErrorBoundary from '@/components/documentation/markdown-error-boundary';
import FileList from '@/components/documentation/file-list';
import ImageUploader from '@/components/documentation/image-uploader';
import { documentService, categoryService } from '@/lib/api/services/documentation-service';
import { fileService } from '@/lib/api/services/file-service';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog';
import {
  Save,
  ArrowLeft,
  Eye,
  FileText,
  Settings,
  Upload,
  Paperclip
} from 'lucide-react';
import { cn } from '@/lib/utils';

const DocEditorPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const isEdit = !!id;

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    slug: '',
    summary: '',
    content: '',
    contentPath: '',
    contentUrl: '',
    contentBase64: '',
    contentType: 'direct', // 'direct' | 'path' | 'url' | 'base64'
    categoryId: '',
    tags: '',
    status: 'draft',
    isPublic: true
  });

  // UI 状态
  const [errors, setErrors] = useState({});
  const [showPreview, setShowPreview] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  
  // Phase 3: 附件管理状态
  const [showUploadDialog, setShowUploadDialog] = useState(false);

  // 获取文档数据（编辑模式）
  const { data: docData, isLoading } = useQuery({
    queryKey: ['documents', 'detail', id],
    queryFn: () => documentService.getById(id),
    enabled: isEdit
  });

  // 获取分类数据
  const { data: categoriesData } = useQuery({
    queryKey: ['documents', 'categories'],
    queryFn: () => categoryService.getAll()
  });

  // Phase 3: 获取文档关联的文件列表（仅在编辑模式下）
  const {
    data: filesData,
    isLoading: filesLoading,
    refetch: refetchFiles
  } = useQuery({
    queryKey: ['files', 'document', id],
    queryFn: () => fileService.getByDocumentId(id),
    enabled: isEdit && !!id,
    staleTime: 30000 // 缓存30秒
  });

  const files = filesData || [];

  // 填充编辑数据
  useEffect(() => {
    // docData 已经是 result.data，不需要再访问 .data
    if (docData) {
      const doc = docData;
      setFormData({
        title: doc.title || '',
        slug: doc.slug || '',
        summary: doc.summary || '',
        content: doc.content || '',
        contentPath: doc.contentPath || '',
        contentUrl: doc.contentUrl || '',
        contentBase64: doc.contentBase64 || '',
        contentType: doc.contentType || 'direct',
        categoryId: doc.categoryId ? String(doc.categoryId) : '',
        tags: doc.tags ? doc.tags.join(', ') : '',
        status: doc.status || 'draft',
        isPublic: doc.isPublic !== false
      });
    }
  }, [docData]);

  // 保存文档
  const saveMutation = useMutation({
    mutationFn: (data) => {
      const payload = {
        title: data.title,
        slug: data.slug,
        summary: data.summary,
        contentType: data.contentType,
        categoryId: data.categoryId ? parseInt(data.categoryId) : null,
        tags: data.tags ? data.tags.split(',').map(t => t.trim()).filter(Boolean) : [],
        status: data.status,
        isPublic: data.isPublic
      };

      // 根据 contentType 设置对应的内容字段
      if (data.contentType === 'direct') {
        payload.content = data.content;
      } else if (data.contentType === 'path') {
        payload.contentPath = data.contentPath;
      } else if (data.contentType === 'url') {
        payload.contentUrl = data.contentUrl;
      } else if (data.contentType === 'base64') {
        payload.contentBase64 = data.contentBase64;
      }

      return isEdit
        ? documentService.update(id, payload)
        : documentService.create(payload);
    },
    onSuccess: (response) => {
      queryClient.invalidateQueries(['documents']);
      setHasUnsavedChanges(false);

      // 跳转到文档详情页
      // response 可能是直接的数据对象，也可能是 { data: {...} } 结构
      const docData = response?.data || response;
      const slug = docData?.slug;
      
      if (slug) {
        navigate(`/documentation/${slug}`, {
          state: { message: isEdit ? '文档已更新' : '文档已创建' }
        });
      } else {
        // 如果没有 slug，返回列表页
        console.warn('保存成功但未返回 slug，返回列表页');
        navigate('/documentation/list');
      }
    },
    onError: (error) => {
      console.error('保存失败:', error);
      setErrors({ submit: error.message || '保存失败，请重试' });
    }
  });

  // 表单变化处理
  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setHasUnsavedChanges(true);

    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: null }));
    }

    // 自动生成 slug
    if (field === 'title' && !isEdit) {
      const slug = value
        .toLowerCase()
        .replace(/[^\w\s-]/g, '')
        .replace(/\s+/g, '-')
        .substring(0, 100);
      setFormData(prev => ({ ...prev, slug }));
    }
  };

  // 表单验证
  const validate = () => {
    const newErrors = {};

    if (!formData.title.trim()) {
      newErrors.title = '请输入文档标题';
    }

    if (!formData.slug.trim()) {
      newErrors.slug = '请输入文档 Slug';
    }

    // 根据 contentType 验证对应的字段
    if (formData.contentType === 'direct' && !formData.content.trim()) {
      newErrors.content = '请输入文档内容';
    } else if (formData.contentType === 'path' && !formData.contentPath.trim()) {
      newErrors.contentPath = '请输入文件路径';
    } else if (formData.contentType === 'url' && !formData.contentUrl.trim()) {
      newErrors.contentUrl = '请输入内容 URL';
    } else if (formData.contentType === 'base64' && !formData.contentBase64.trim()) {
      newErrors.contentBase64 = '请输入 Base64 编码内容';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 保存处理
  const handleSave = async (status = formData.status) => {
    if (!validate()) {
      return;
    }

    saveMutation.mutate({ ...formData, status });
  };

  // 离开页面提醒
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      if (hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges]);

  // 获取所有分类（扁平化）
  const allCategories = React.useMemo(() => {
    // 处理 Mock 和 API 的不同数据结构
    const categories = Array.isArray(categoriesData)
      ? categoriesData
      : (categoriesData?.data || []);
    
    const flatten = [];
    categories.forEach(cat => {
      flatten.push({ id: cat.id, name: cat.name });
      if (cat.children) {
        cat.children.forEach(child => {
          flatten.push({
            id: child.id,
            name: `${cat.name} / ${child.name}`
          });
        });
      }
    });
    return flatten;
  }, [categoriesData]);

  // 加载状态（仅在编辑模式下检查）
  if (isEdit && isLoading) {
    return (
      <Container className="py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">加载中...</p>
          </div>
        </div>
      </Container>
    );
  }

  return (
    <MarkdownErrorBoundary>
      <Container className="py-8">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Link to="/documentation">
              <Button variant="ghost" size="sm">
                <ArrowLeft className="size-4 mr-2" />
                返回
              </Button>
            </Link>
            <div>
              <h1 className="text-3xl font-bold">
                {isEdit ? '编辑文档' : '新建文档'}
              </h1>
              {hasUnsavedChanges && (
                <Badge variant="secondary" className="mt-1">
                  有未保存的更改
                </Badge>
              )}
            </div>
          </div>

        {/* 操作按钮 */}
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            onClick={() => handleSave('draft')}
            disabled={saveMutation.isPending}
          >
            <Save className="size-4 mr-2" />
            保存草稿
          </Button>
          <Button
            onClick={() => handleSave('published')}
            disabled={saveMutation.isPending}
          >
            <Save className="size-4 mr-2" />
            {saveMutation.isPending ? '保存中...' : '发布'}
          </Button>
        </div>
      </div>

      {/* 错误提示 */}
      {errors.submit && (
        <div className="mb-6 p-4 bg-destructive/10 text-destructive rounded-lg">
          {errors.submit}
        </div>
      )}

      {/* 表单内容 */}
      <Tabs defaultValue="edit" className="space-y-6">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="edit">
            <FileText className="size-4 mr-2" />
            编辑
          </TabsTrigger>
          <TabsTrigger value="preview">
            <Eye className="size-4 mr-2" />
            预览
          </TabsTrigger>
          <TabsTrigger value="settings">
            <Settings className="size-4 mr-2" />
            设置
          </TabsTrigger>
        </TabsList>

        {/* 编辑标签页 */}
        <TabsContent value="edit" className="space-y-6">
          {/* 基本信息 */}
          <Card>
            <CardHeader>
              <CardTitle>基本信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 标题 */}
              <div className="space-y-2">
                <Label htmlFor="title">
                  文档标题 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => handleChange('title', e.target.value)}
                  placeholder="请输入文档标题"
                  className={errors.title ? 'border-destructive' : ''}
                />
                {errors.title && (
                  <p className="text-sm text-destructive">{errors.title}</p>
                )}
              </div>

              {/* Slug */}
              <div className="space-y-2">
                <Label htmlFor="slug">
                  URL Slug <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="slug"
                  value={formData.slug}
                  onChange={(e) => handleChange('slug', e.target.value)}
                  placeholder="url-friendly-slug"
                  className={errors.slug ? 'border-destructive' : ''}
                />
                <p className="text-xs text-muted-foreground">
                  将作为 URL 的一部分，如：/documentation/{formData.slug || 'your-slug'}
                </p>
                {errors.slug && (
                  <p className="text-sm text-destructive">{errors.slug}</p>
                )}
              </div>

              {/* 摘要 */}
              <div className="space-y-2">
                <Label htmlFor="summary">文档摘要</Label>
                <Textarea
                  id="summary"
                  value={formData.summary}
                  onChange={(e) => handleChange('summary', e.target.value)}
                  placeholder="简要描述文档内容（可选）"
                  rows={3}
                />
              </div>
            </CardContent>
          </Card>

          {/* 文档内容 */}
          <Card>
            <CardHeader>
              <CardTitle>文档内容</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 内容来源类型选择 */}
              <div className="space-y-2">
                <Label htmlFor="contentType">内容来源</Label>
                <Select
                  value={formData.contentType}
                  onValueChange={(value) => handleChange('contentType', value)}
                >
                  <SelectTrigger id="contentType">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="direct">
                      <div className="flex flex-col">
                        <span className="font-medium">直接输入</span>
                        <span className="text-xs text-muted-foreground">使用编辑器直接编写 Markdown</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="path">
                      <div className="flex flex-col">
                        <span className="font-medium">项目文件</span>
                        <span className="text-xs text-muted-foreground">引用项目内的 Markdown 文件</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="url">
                      <div className="flex flex-col">
                        <span className="font-medium">外部 URL</span>
                        <span className="text-xs text-muted-foreground">MinIO 或其他外部链接</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="base64">
                      <div className="flex flex-col">
                        <span className="font-medium">Base64 编码</span>
                        <span className="text-xs text-muted-foreground">Base64 编码的内容</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 直接输入 - Monaco 编辑器 */}
              {formData.contentType === 'direct' && (
                <div className="space-y-2">
                  <MonacoMarkdownEditor
                    documentId={isEdit ? id : null}
                    value={formData.content}
                    onChange={(value) => handleChange('content', value)}
                    onSave={() => handleSave()}
                    height="600px"
                  />
                  {errors.content && (
                    <p className="text-sm text-destructive">{errors.content}</p>
                  )}
                </div>
              )}

              {/* 项目文件路径 */}
              {formData.contentType === 'path' && (
                <div className="space-y-2">
                  <Label htmlFor="contentPath">
                    文件路径 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="contentPath"
                    value={formData.contentPath}
                    onChange={(e) => handleChange('contentPath', e.target.value)}
                    placeholder="/docs/api-guide.md"
                    className={errors.contentPath ? 'border-destructive' : ''}
                  />
                  <p className="text-xs text-muted-foreground">
                    项目内相对路径，如：<code className="px-1 py-0.5 bg-muted rounded">/docs/guide.md</code>
                  </p>
                  {errors.contentPath && (
                    <p className="text-sm text-destructive">{errors.contentPath}</p>
                  )}
                </div>
              )}

              {/* 外部 URL */}
              {formData.contentType === 'url' && (
                <div className="space-y-2">
                  <Label htmlFor="contentUrl">
                    内容 URL <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="contentUrl"
                    value={formData.contentUrl}
                    onChange={(e) => handleChange('contentUrl', e.target.value)}
                    placeholder="https://minio.example.com/docs/api-reference.md"
                    className={errors.contentUrl ? 'border-destructive' : ''}
                  />
                  <p className="text-xs text-muted-foreground">
                    外部 Markdown 文件链接，如：MinIO 对象存储、GitHub 原始文件链接
                  </p>
                  {errors.contentUrl && (
                    <p className="text-sm text-destructive">{errors.contentUrl}</p>
                  )}
                </div>
              )}

              {/* Base64 编码 */}
              {formData.contentType === 'base64' && (
                <div className="space-y-2">
                  <Label htmlFor="contentBase64">
                    Base64 内容 <span className="text-destructive">*</span>
                  </Label>
                  <Textarea
                    id="contentBase64"
                    value={formData.contentBase64}
                    onChange={(e) => handleChange('contentBase64', e.target.value)}
                    placeholder="IyDmtYvor5XmlofmoaM="
                    rows={10}
                    className={cn('font-mono text-xs', errors.contentBase64 ? 'border-destructive' : '')}
                  />
                  <p className="text-xs text-muted-foreground">
                    Base64 编码的 Markdown 内容
                  </p>
                  {errors.contentBase64 && (
                    <p className="text-sm text-destructive">{errors.contentBase64}</p>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 预览标签页 */}
        <TabsContent value="preview">
          <Card>
            <CardHeader>
              <CardTitle>{formData.title || '无标题'}</CardTitle>
              {formData.summary && (
                <p className="text-muted-foreground mt-2">{formData.summary}</p>
              )}
              <div className="flex items-center gap-2 mt-2">
                <Badge variant="outline">{
                  formData.contentType === 'direct' ? '直接输入' :
                  formData.contentType === 'path' ? '项目文件' :
                  formData.contentType === 'url' ? '外部 URL' :
                  'Base64 编码'
                }</Badge>
                {formData.contentType === 'path' && formData.contentPath && (
                  <code className="text-xs px-2 py-1 bg-muted rounded">{formData.contentPath}</code>
                )}
                {formData.contentType === 'url' && formData.contentUrl && (
                  <code className="text-xs px-2 py-1 bg-muted rounded truncate max-w-md">{formData.contentUrl}</code>
                )}
              </div>
            </CardHeader>
            <CardContent>
              {formData.contentType === 'direct' && (
                <MarkdownRenderer content={formData.content || '*暂无内容*'} />
              )}
              {formData.contentType === 'path' && (
                <div className="p-4 bg-muted rounded-lg">
                  <p className="text-sm text-muted-foreground mb-2">📂 文件路径预览：</p>
                  <code className="text-sm">{formData.contentPath || '未设置文件路径'}</code>
                  <p className="text-xs text-muted-foreground mt-4">
                    💡 实际内容将从该文件动态加载
                  </p>
                </div>
              )}
              {formData.contentType === 'url' && (
                <div className="p-4 bg-muted rounded-lg">
                  <p className="text-sm text-muted-foreground mb-2">🌐 外部 URL 预览：</p>
                  <code className="text-sm break-all">{formData.contentUrl || '未设置 URL'}</code>
                  <p className="text-xs text-muted-foreground mt-4">
                    💡 实际内容将从该 URL 动态获取
                  </p>
                </div>
              )}
              {formData.contentType === 'base64' && (
                <div className="p-4 bg-muted rounded-lg">
                  <p className="text-sm text-muted-foreground mb-2">🔐 Base64 编码预览：</p>
                  <code className="text-xs font-mono break-all max-h-32 overflow-y-auto block">
                    {formData.contentBase64 ? formData.contentBase64.substring(0, 200) + '...' : '未设置 Base64 内容'}
                  </code>
                  <p className="text-xs text-muted-foreground mt-4">
                    💡 实际内容将解码后显示
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 设置标签页 */}
        <TabsContent value="settings" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>文档设置</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 分类 */}
              <div className="space-y-2">
                <Label htmlFor="category">分类</Label>
                <Select
                  value={formData.categoryId}
                  onValueChange={(value) => handleChange('categoryId', value)}
                >
                  <SelectTrigger id="category">
                    <SelectValue placeholder="选择分类" />
                  </SelectTrigger>
                  <SelectContent>
                    {allCategories.map(cat => (
                      <SelectItem key={cat.id} value={String(cat.id)}>
                        {cat.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 标签 */}
              <div className="space-y-2">
                <Label htmlFor="tags">标签</Label>
                <Input
                  id="tags"
                  value={formData.tags}
                  onChange={(e) => handleChange('tags', e.target.value)}
                  placeholder="多个标签用逗号分隔，如：React, JavaScript, 教程"
                />
              </div>

              {/* 状态 */}
              <div className="space-y-2">
                <Label htmlFor="status">状态</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value) => handleChange('status', value)}
                >
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="draft">草稿</SelectItem>
                    <SelectItem value="published">已发布</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 公开性 */}
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="isPublic"
                  checked={formData.isPublic}
                  onChange={(e) => handleChange('isPublic', e.target.checked)}
                  className="rounded"
                />
                <Label htmlFor="isPublic" className="cursor-pointer">
                  公开文档（所有人可见）
                </Label>
              </div>
            </CardContent>
          </Card>

        {/* Phase 3: 附件管理（仅在编辑模式下显示） */}
        {isEdit && (
          <Card>
            <CardHeader className="flex items-center justify-between">
              <CardTitle className="flex items-center gap-2">
                <Paperclip className="size-5" />
                文档附件 ({files.length})
              </CardTitle>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowUploadDialog(true)}
                className="ml-auto"
              >
                <Upload className="size-4 mr-2" />
                上传附件
              </Button>
            </CardHeader>
              <CardContent>
                <FileList
                  files={files}
                  documentId={id}
                  isLoading={filesLoading}
                  onRefresh={refetchFiles}
                  allowEdit={true}
                  markdownContent={formData.contentType === 'direct' ? formData.content : ''}
                />
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>

      {/* Phase 3: 上传附件对话框 */}
      {isEdit && (
        <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>上传附件</DialogTitle>
              <DialogDescription>
                支持图片、PDF、Word、Excel 等文件格式，最大 10MB
              </DialogDescription>
            </DialogHeader>
            <ImageUploader
              onSuccess={(fileMetadata) => {
                setShowUploadDialog(false);
                refetchFiles();
              }}
              onError={(error) => {
                console.error('上传失败:', error);
              }}
              documentId={id}
              fileType="document"
              compress={false}
              maxSizeMB={10}
              accept="*/*"
              uploadSource="attachment"  // 文档附件上传
            />
          </DialogContent>
        </Dialog>
      )}
      </Container>
    </MarkdownErrorBoundary>
  );
};

export default DocEditorPage;

